import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { dailyLearningApi, debateApi } from '../services/api'
import type { Question, DebateSession } from '../types'
import DebatePanel from './DebatePanel'
import './DailyLearningPanel.css'

interface DailyLearningPanelProps {
  userId: string
  planId?: string
  userStatus?: any
  onPlanCreated?: (planId: string) => void
  onNavigate?: (tab: string) => void  // 导航回调
}

interface AnswerRecord {
  question_id: string
  user_answer: string
  correct_answer?: string
  is_correct: boolean
  marked_wrong: boolean
  user_notes?: string
  error_analysis?: {
    error_type: string
    error_category: string
    user_notes?: string
    system_analysis: string
  }
  unmastered_knowledge_points?: string[]
  thinking_analysis?: {
    thinking_quality_score: number
    strengths: string[]
    weaknesses: string[]
    thinking_pattern: string
    reasoning_chain: string
    improvement_suggestions: string[]
    legal_knowledge_gaps: string[]
  }
  detailed_analysis?: string | {
    detailed_analysis?: string
    thinking_approach?: string
    correct_answer_explanation?: string
    error_analysis?: string
    knowledge_points?: string[]
    reinforcement_suggestions?: string[]
  }  // 详细分析（答对时：做题思路和为什么正确；答错时：错误分析）
  recommendations?: string[]
}

const DailyLearningPanel = ({ userId, planId, userStatus, onPlanCreated, onNavigate }: DailyLearningPanelProps) => {
  const [dailyQuestions, setDailyQuestions] = useState<Question[]>([])
  const [currentIndex, setCurrentIndex] = useState(0)
  const [selectedAnswer, setSelectedAnswer] = useState<string>('')
  const [selectedAnswers, setSelectedAnswers] = useState<string[]>([]) // 多选题选中的答案数组
  const [userNotes, setUserNotes] = useState<string>('')
  const [markedWrong, setMarkedWrong] = useState(false)
  const [answerResult, setAnswerResult] = useState<AnswerRecord | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [dailyTask, setDailyTask] = useState<any>(null)
  const [answers, setAnswers] = useState<Record<string, AnswerRecord>>({})
  const [forceShowQuestions, setForceShowQuestions] = useState(false)  // 强制显示题目，跳过状态检查
  const [showDebate, setShowDebate] = useState(false)
  const [debateSession, setDebateSession] = useState<DebateSession | null>(null)

  // 加载每日题目
  useEffect(() => {
    loadDailyQuestions()
  }, [userId, planId, userStatus])
  
  // 当有题目时，自动设置forceShowQuestions（优先级最高）
  useEffect(() => {
    if (dailyQuestions.length > 0 && dailyTask) {
      console.log('🔍 [DailyLearningPanel] 检测到题目已加载，自动设置forceShowQuestions=true')
      setForceShowQuestions(true)
    }
  }, [dailyQuestions.length, dailyTask])
  
  // 当planId变化时，如果有题目，也设置forceShowQuestions
  useEffect(() => {
    if (planId && dailyQuestions.length > 0) {
      console.log('🔍 [DailyLearningPanel] planId已设置且有题目，设置forceShowQuestions=true')
      setForceShowQuestions(true)
    }
  }, [planId, dailyQuestions.length])

  const loadDailyQuestions = async () => {
    // 检查用户状态
    if (userStatus) {
      const status = userStatus as any
      if (status.current_stage === 'first_visit') {
        // 首次访问，引导去测试
        return
      }
      if (status.current_stage === 'test_completed') {
        // 测试完成但未创建计划，引导创建计划
        return
      }
      if (status.plan_id && !planId) {
        // 有激活的计划但props中没有，使用状态中的计划ID
        const task = await dailyLearningApi.getDailyQuestions(userId, status.plan_id)
        setDailyTask(task)
        setDailyQuestions((task as any).questions || [])
        return
      }
    }

    if (!planId) {
      // 如果没有计划ID，尝试获取激活的计划
      return
    }

    setIsLoading(true)
    try {
      const task = await dailyLearningApi.getDailyQuestions(userId, planId)
      setDailyTask(task)
      setDailyQuestions((task as any).questions || [])
      
      // 检查是否真的完成了（已完成数量 >= 目标数量）
      const taskData = task as any
      if (taskData.status === 'completed' && taskData.completed_questions >= taskData.target_questions) {
        // 确实完成了
      } else if (taskData.questions && taskData.questions.length === 0 && taskData.completed_questions < taskData.target_questions) {
        // 题目列表为空但未完成，可能是加载问题，重新加载
        console.warn('题目列表为空但未完成，可能是数据问题')
      }
    } catch (error) {
      console.error('加载每日题目失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 处理选项点击（支持单选和多选）
  const handleOptionClick = (option: string) => {
    const currentQuestion = dailyQuestions[currentIndex]
    if (!currentQuestion) return
    
    const isMultipleChoice = currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice'
    
    if (isMultipleChoice) {
      // 多选题：切换选中状态
      setSelectedAnswers(prev => {
        if (prev.includes(option)) {
          // 如果已选中，则取消选中
          return prev.filter(item => item !== option)
        } else {
          // 如果未选中，则添加到选中列表
          return [...prev, option]
        }
      })
    } else {
      // 单选题：直接设置选中答案
      setSelectedAnswer(option)
    }
  }

  // 提交答案
  const submitAnswer = async () => {
    if (!dailyTask) return

    const currentQuestion = dailyQuestions[currentIndex]
    if (!currentQuestion) return

    const isMultipleChoice = currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice'
    const finalAnswer = isMultipleChoice 
      ? (selectedAnswers.length > 0 ? selectedAnswers.join('、') : '') // 多选题用"、"连接
      : selectedAnswer

    if (!finalAnswer) return

    setIsLoading(true)
    try {
      const result = await dailyLearningApi.submitDailyAnswer(
        userId,
        (dailyTask as any).plan_id,
        currentQuestion.question_id,
        finalAnswer,
        userNotes || undefined,
        markedWrong
      )

      const answerRecord: AnswerRecord = {
        question_id: currentQuestion.question_id,
        user_answer: finalAnswer,
        correct_answer: (result as any).correct_answer,
        is_correct: (result as any).is_correct,
        marked_wrong: markedWrong,
        user_notes: userNotes,
        error_analysis: (result as any).error_analysis,
        unmastered_knowledge_points: (result as any).unmastered_knowledge_points,
        thinking_analysis: (result as any).thinking_analysis,
        detailed_analysis: (result as any).detailed_analysis,  // 详细分析（答对时：做题思路和为什么正确；答错时：错误分析）
        recommendations: (result as any).recommendations,
      }

      setAnswers({
        ...answers,
        [currentQuestion.question_id]: answerRecord,
      })
      setAnswerResult(answerRecord)
    } catch (error) {
      console.error('提交答案失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 下一题
  const nextQuestion = () => {
    if (currentIndex < dailyQuestions.length - 1) {
      setCurrentIndex(currentIndex + 1)
      setSelectedAnswer('')
      setSelectedAnswers([]) // 重置多选题答案
      setUserNotes('')
      setMarkedWrong(false)
      setAnswerResult(null)
    }
  }

  // 上一题
  const prevQuestion = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1)
      const prevQuestion = dailyQuestions[currentIndex - 1]
      const prevAnswer = answers[prevQuestion.question_id]
      if (prevAnswer) {
        // 判断上一题是多选题还是单选题
        const isMultipleChoice = prevQuestion.type === 'multiple_choice' || prevQuestion.type === 'indefinite_choice'
        if (isMultipleChoice) {
          // 多选题：将答案字符串（用"、"分隔）解析为数组
          setSelectedAnswers(prevAnswer.user_answer ? prevAnswer.user_answer.split('、') : [])
          setSelectedAnswer('')
        } else {
          // 单选题：直接设置答案
          setSelectedAnswer(prevAnswer.user_answer || '')
          setSelectedAnswers([])
        }
        setUserNotes(prevAnswer.user_notes || '')
        setMarkedWrong(prevAnswer.marked_wrong)
        setAnswerResult(prevAnswer)
      } else {
        setSelectedAnswer('')
        setSelectedAnswers([])
        setUserNotes('')
        setMarkedWrong(false)
        setAnswerResult(null)
      }
    }
  }

  const currentQuestion = dailyQuestions[currentIndex]

  // 调试日志
  console.log('🔍 [DailyLearningPanel] 渲染状态:', {
    userId,
    planId,
    userStatus: userStatus ? {
      current_stage: (userStatus as any).current_stage,
      has_plan: (userStatus as any).has_plan,
      plan_id: (userStatus as any).plan_id
    } : null,
    forceShowQuestions,
    dailyQuestionsCount: dailyQuestions.length,
    dailyTask: dailyTask ? {
      total_questions: (dailyTask as any).total_questions,
      target_questions: (dailyTask as any).target_questions,
      completed_questions: (dailyTask as any).completed_questions,
      status: (dailyTask as any).status
    } : null,
    isLoading,
    currentIndex
  })

  // 优先级1: 如果有题目，直接显示（跳过所有状态检查）
  if (dailyQuestions.length > 0) {
    console.log('🔍 [DailyLearningPanel] 有题目数据，直接显示，跳过状态检查')
    // 继续执行到题目显示部分
  }
  // 优先级2: 检查用户状态（只有在没有题目时才检查）
  else if (userStatus && !forceShowQuestions && dailyQuestions.length === 0) {
    console.log('🔍 [DailyLearningPanel] 检查用户状态，current_stage:', (userStatus as any).current_stage)
    const status = userStatus as any
    if (status.current_stage === 'first_visit') {
      return (
        <div className="daily-learning-empty">
          <p>🎮 欢迎来到AI法考备考软件！</p>
          <p className="hint">让我们先通过一个小测试来了解您的法律知识水平</p>
          <button 
            className="action-button primary"
            onClick={() => {
              // 导航到模拟测试
              if (onNavigate) {
                onNavigate('mock-exam')
              } else {
                // 如果没有回调，尝试使用hash（兼容性）
                window.location.hash = 'mock-exam'
              }
            }}
          >
            开始测试
          </button>
        </div>
      )
    }
    if (status.current_stage === 'test_completed') {
      console.log('🔍 [DailyLearningPanel] 渲染"创建学习计划"按钮界面')
      return (
        <div className="daily-learning-empty">
          <p>✅ 测试完成！</p>
          <p className="hint">现在让我们为您创建一个个性化的学习计划</p>
          <button 
            className="action-button primary"
            onClick={(e) => {
              console.log('🔵 [创建计划] 按钮被点击 - 事件对象:', e)
              console.log('🔵 [创建计划] 按钮被点击 - 当前状态:', {
                isLoading,
                userId,
                userStatus: status
              })
              // 立即执行异步函数
              ;(async () => {
                console.log('🔵 [创建计划] 按钮被点击 - 异步函数开始执行')
              // 根据测试结果自动创建学习计划并开始学习
              try {
                console.log('🔵 [创建计划] 开始执行，设置loading状态')
                setIsLoading(true)
                
                console.log('🔵 [创建计划] 步骤1: 获取测试结果')
                // 获取测试结果
                const { userStatusApi, assessmentApi, dailyLearningApi } = await import('../services/api')
                console.log('🔵 [创建计划] API模块已导入')
                
                const testResult = await userStatusApi.getTestResult(userId)
                console.log('🔵 [创建计划] 测试结果:', testResult)
                
                // 根据测试结果推荐学习天数
                let recommendedDays = 180
                if (testResult && (testResult as any).test_result) {
                  const accuracy = (testResult as any).test_result.accuracy || 0
                  console.log('🔵 [创建计划] 测试准确率:', accuracy)
                  if (accuracy >= 80) {
                    recommendedDays = 60  // 高分用户，冲刺计划
                  } else if (accuracy >= 65) {
                    recommendedDays = 90  // 中等水平，强化计划
                  } else {
                    recommendedDays = 180  // 基础薄弱，标准计划
                  }
                }
                console.log('🔵 [创建计划] 推荐学习天数:', recommendedDays)
                
                console.log('🔵 [创建计划] 步骤2: 创建学习计划')
                // 创建学习计划
                const plan = await assessmentApi.createStudyPlan(recommendedDays, userId)
                console.log('🔵 [创建计划] 计划创建成功:', plan)
                
                console.log('🔵 [创建计划] 步骤3: 激活计划')
                // 激活计划
                const activateResult = await dailyLearningApi.activatePlan(plan.plan_id, userId)
                console.log('🔵 [创建计划] 计划激活成功:', activateResult)
                
                console.log('🔵 [创建计划] 步骤4: 获取每日题目')
                // 更新本地状态，使用新创建的计划ID
                const updatedTask = await dailyLearningApi.getDailyQuestions(userId, plan.plan_id)
                console.log('🔵 [创建计划] 每日题目获取成功:', updatedTask)
                console.log('🔵 [创建计划] 题目数量:', (updatedTask as any).questions?.length || 0)
                
                // 先设置题目数据
                const questions = (updatedTask as any).questions || []
                setDailyTask(updatedTask)
                setDailyQuestions(questions)
                console.log('🔵 [创建计划] 本地状态已更新，题目数量:', questions.length)
                
                // 强制显示题目，跳过userStatus检查（必须在设置题目之后）
                if (questions.length > 0) {
                  setForceShowQuestions(true)
                  console.log('🔵 [创建计划] 已设置forceShowQuestions=true（因为有题目）')
                } else {
                  console.warn('🔵 [创建计划] 警告：题目列表为空！')
                }
                
                // 触发回调，通知父组件计划已创建（这会更新userStatus，但不会影响forceShowQuestions）
                if (onPlanCreated) {
                  console.log('🔵 [创建计划] 触发onPlanCreated回调，planId:', plan.plan_id)
                  // 使用setTimeout确保状态更新完成后再触发回调
                  setTimeout(() => {
                    onPlanCreated(plan.plan_id)
                  }, 100)
                } else {
                  console.warn('🔵 [创建计划] onPlanCreated回调不存在')
                }
                
                // 重置状态
                setAnswerResult(null)
                setCurrentIndex(0)
                setSelectedAnswer('')
                setUserNotes('')
                setMarkedWrong(false)
                console.log('🔵 [创建计划] 所有状态已重置')
                console.log('✅ [创建计划] 完成！应该显示题目了')
              } catch (error) {
                console.error('❌ [创建计划] 失败:', error)
                console.error('❌ [创建计划] 错误详情:', {
                  message: (error as any).message,
                  response: (error as any).response?.data,
                  status: (error as any).response?.status
                })
                alert('创建学习计划失败，请稍后重试\n\n错误信息: ' + ((error as any).message || '未知错误'))
                // 如果失败，导航到评估诊断页面手动创建
                if (onNavigate) {
                  onNavigate('assessment')
                } else {
                  window.location.hash = 'assessment'
                }
              } finally {
                console.log('🔵 [创建计划] 清理loading状态')
                setIsLoading(false)
              }
              })()
            }}
            disabled={isLoading}
            style={{ 
              cursor: isLoading ? 'not-allowed' : 'pointer',
              opacity: isLoading ? 0.6 : 1
            }}
          >
            {isLoading ? '创建中...' : '创建学习计划'}
          </button>
        </div>
      )
    }
  }

  // 如果有题目数据，即使没有planId也显示（可能是刚创建的）
  if (!planId && (!userStatus || !(userStatus as any).plan_id) && dailyQuestions.length === 0 && !forceShowQuestions) {
    console.log('🔍 [DailyLearningPanel] 没有计划且没有题目，显示创建计划提示')
    return (
      <div className="daily-learning-empty">
        <p>请先创建学习计划</p>
        <p className="hint">在"评估诊断"中创建学习计划后即可开始每日学习</p>
        <button 
          className="action-button primary"
          onClick={() => {
            if (onNavigate) {
              onNavigate('assessment')
            } else {
              window.location.hash = 'assessment'
            }
          }}
        >
          去创建计划
        </button>
      </div>
    )
  }

  if (isLoading && dailyQuestions.length === 0 && !forceShowQuestions) {
    console.log('🔍 [DailyLearningPanel] 显示加载状态')
    return (
      <div className="daily-learning-loading">
        <div className="loading-spinner"></div>
        <p>加载今日题目中...</p>
      </div>
    )
  }

  // 检查是否真的完成了
  const taskData = dailyTask as any
  if (taskData && taskData.status === 'completed' && taskData.completed_questions >= taskData.target_questions) {
    console.log('🔍 [DailyLearningPanel] 任务已完成，显示完成界面')
    return (
      <div className="daily-learning-empty">
        <p>🎉 今日学习任务已完成！</p>
        <p className="hint">明天继续加油 💪</p>
        {taskData.progress && (
          <div className="progress-summary">
            <p>完成进度: {Math.round(taskData.progress * 100)}%</p>
            <p>已完成: {taskData.completed_questions} / {taskData.target_questions} 题</p>
          </div>
        )}
      </div>
    )
  }

  if (dailyQuestions.length === 0 && (!taskData || taskData.status !== 'completed') && !forceShowQuestions) {
    console.log('🔍 [DailyLearningPanel] 题目列表为空，显示加载状态')
    return (
      <div className="daily-learning-loading">
        <div className="loading-spinner"></div>
        <p>正在准备今日题目...</p>
      </div>
    )
  }
  
  // 如果强制显示但题目为空，显示提示
  if (forceShowQuestions && dailyQuestions.length === 0) {
    console.log('🔍 [DailyLearningPanel] 强制显示但题目为空')
    return (
      <div className="daily-learning-empty">
        <p>⚠️ 题目加载中...</p>
        <p className="hint">请稍候，正在为您准备今日学习题目</p>
        <button 
          className="action-button"
          onClick={() => {
            loadDailyQuestions()
          }}
        >
          重新加载
        </button>
      </div>
    )
  }

  // 如果题目已加载，显示题目界面（这是最终显示题目的地方）
  if (dailyQuestions.length > 0) {
    console.log('🔍 [DailyLearningPanel] 显示题目界面，题目数量:', dailyQuestions.length)
  }
  
  return (
    <div className="daily-learning-panel">
      {/* 顶部信息 */}
      <div className="daily-header">
        <div className="daily-progress">
          <span>
            今日进度: {currentIndex + 1} / {dailyQuestions.length}
          </span>
          <div className="progress-bar">
            <div
              className="progress-fill"
              style={{
                width: `${((currentIndex + 1) / dailyQuestions.length) * 100}%`,
              }}
            ></div>
          </div>
        </div>
        <div className="daily-date">
          {new Date().toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
          })}
        </div>
      </div>

      {/* 题目区域 */}
      {currentQuestion && !answerResult && (
        <motion.div
          key={currentQuestion.question_id}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          className="question-card"
        >
          <div className="question-header">
            <span className="question-category">{currentQuestion.category || '综合'}</span>
            <span className="question-difficulty">{currentQuestion.difficulty || 'medium'}</span>
          </div>

          <div className="question-content">
            <h3>{currentQuestion.content}</h3>
          </div>

          {currentQuestion.options && (
            <div className="options-list">
              <div className="question-type-hint">
                {currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice' 
                  ? '📌 多选题：可以选择多个选项' 
                  : '📌 单选题：只能选择一个选项'}
              </div>
              {currentQuestion.options.map((option, index) => (
                <button
                  key={index}
                  className={`option-button ${
                    (currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice')
                      ? (selectedAnswers.includes(option) ? 'selected' : '')
                      : (selectedAnswer === option ? 'selected' : '')
                  }`}
                  onClick={() => handleOptionClick(option)}
                >
                  {(currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice') && selectedAnswers.includes(option) && '✓ '}
                  {option}
                </button>
              ))}
            </div>
          )}

          {/* 标记错误和备注 */}
          <div className="answer-actions">
            <label className="checkbox-label">
              <input
                type="checkbox"
                checked={markedWrong}
                onChange={(e) => setMarkedWrong(e.target.checked)}
              />
              <span>标记为错误（即使答案正确）</span>
            </label>

            <div className="notes-section">
              <label>我的分析（可选）：</label>
              <textarea
                className="notes-input"
                placeholder="记录你的思考过程、疑惑点或分析..."
                value={userNotes}
                onChange={(e) => setUserNotes(e.target.value)}
                rows={3}
              />
            </div>
          </div>

          {/* 提交按钮 */}
          <div className="question-actions">
            <button
              className="submit-button"
              onClick={submitAnswer}
              disabled={
                (currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice')
                  ? selectedAnswers.length === 0
                  : !selectedAnswer
                || isLoading
              }
            >
              {isLoading ? '提交中...' : '提交答案'}
            </button>
          </div>
        </motion.div>
      )}

      {/* 答案结果 */}
      <AnimatePresence>
        {answerResult && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className={`result-card ${answerResult.is_correct && !answerResult.marked_wrong ? 'correct' : 'incorrect'}`}
          >
            <div className="result-header">
              <h3>
                {answerResult.is_correct && !answerResult.marked_wrong
                  ? '✓ 回答正确'
                  : '✗ 回答错误'}
              </h3>
            </div>

            <div className="result-content">
              <div className="answer-comparison">
                <div>
                  <strong>你的答案:</strong> {answerResult.user_answer}
                </div>
                <div>
                  <strong>正确答案:</strong> {answerResult.correct_answer || '未提供'}
                </div>
              </div>

              {/* 错误分析 */}
              {answerResult.error_analysis && (
                <div className="error-analysis">
                  <h4>错误分析</h4>
                  <div className="analysis-item">
                    <strong>错误类型:</strong> {answerResult.error_analysis.error_type}
                  </div>
                  <div className="analysis-item">
                    <strong>错误类别:</strong> {answerResult.error_analysis.error_category}
                  </div>
                  {answerResult.error_analysis.user_notes && (
                    <div className="analysis-item">
                      <strong>你的分析:</strong>
                      <p>{answerResult.error_analysis.user_notes}</p>
                    </div>
                  )}
                  {answerResult.error_analysis.system_analysis && (
                    <div className="analysis-item">
                      <strong>系统批注:</strong>
                      <p>{answerResult.error_analysis.system_analysis}</p>
                    </div>
                  )}
                </div>
              )}

              {/* 未掌握的知识点 */}
              {answerResult.unmastered_knowledge_points &&
                answerResult.unmastered_knowledge_points.length > 0 && (
                  <div className="knowledge-points">
                    <h4>未掌握的知识点</h4>
                    <div className="points-list">
                      {answerResult.unmastered_knowledge_points.map((point, index) => (
                        <span key={index} className="knowledge-tag">
                          {point}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

              {/* 法律思维分析 */}
              {answerResult.thinking_analysis && (
                <div className="thinking-analysis">
                  <h4>🧠 法律思维分析</h4>
                  <div className="thinking-score">
                    <div className="score-circle">
                      <span className="score-value">
                        {answerResult.thinking_analysis.thinking_quality_score}
                      </span>
                      <span className="score-label">思维质量</span>
                    </div>
                  </div>
                  
                  {answerResult.thinking_analysis.strengths &&
                    answerResult.thinking_analysis.strengths.length > 0 && (
                      <div className="thinking-strengths">
                        <strong>✅ 思维优势：</strong>
                        <ul>
                          {answerResult.thinking_analysis.strengths.map((strength, index) => (
                            <li key={index}>{strength}</li>
                          ))}
                        </ul>
                      </div>
                    )}
                  
                  {answerResult.thinking_analysis.weaknesses &&
                    answerResult.thinking_analysis.weaknesses.length > 0 && (
                      <div className="thinking-weaknesses">
                        <strong>⚠️ 需要改进：</strong>
                        <ul>
                          {answerResult.thinking_analysis.weaknesses.map((weakness, index) => (
                            <li key={index}>{weakness}</li>
                          ))}
                        </ul>
                      </div>
                    )}
                  
                  {answerResult.thinking_analysis.thinking_pattern && (
                    <div className="thinking-pattern">
                      <strong>思维模式：</strong>
                      <p>{answerResult.thinking_analysis.thinking_pattern}</p>
                    </div>
                  )}
                  
                  {answerResult.thinking_analysis.reasoning_chain && (
                    <div className="reasoning-chain">
                      <strong>推理链条：</strong>
                      <p>{answerResult.thinking_analysis.reasoning_chain}</p>
                    </div>
                  )}
                  
                  {answerResult.thinking_analysis.improvement_suggestions &&
                    answerResult.thinking_analysis.improvement_suggestions.length > 0 && (
                      <div className="thinking-suggestions">
                        <strong>💡 思维训练建议：</strong>
                        <ul>
                          {answerResult.thinking_analysis.improvement_suggestions.map(
                            (suggestion, index) => (
                              <li key={index}>{suggestion}</li>
                            )
                          )}
                        </ul>
                      </div>
                    )}
                </div>
              )}

              {/* 详细分析（答对时：做题思路和为什么正确；答错时：错误分析） */}
              {answerResult.detailed_analysis && (
                <div className="detailed-analysis">
                  <h4>
                    {answerResult.is_correct && !answerResult.marked_wrong
                      ? '✅ 做题思路分析'
                      : '📝 详细错误分析'}
                  </h4>
                  {typeof answerResult.detailed_analysis === 'string' ? (
                    <div className="analysis-content">
                      <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                        {answerResult.detailed_analysis}
                      </pre>
                    </div>
                  ) : (
                    <div className="analysis-content">
                      {answerResult.detailed_analysis.detailed_analysis && (
                        <div className="analysis-text">
                          <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                            {answerResult.detailed_analysis.detailed_analysis}
                          </pre>
                        </div>
                      )}
                      {answerResult.detailed_analysis.thinking_approach && (
                        <div className="thinking-approach">
                          <strong>💭 做题思路：</strong>
                          <p>{answerResult.detailed_analysis.thinking_approach}</p>
                        </div>
                      )}
                      {answerResult.detailed_analysis.correct_answer_explanation && (
                        <div className="correct-explanation">
                          <strong>✅ 为什么正确：</strong>
                          <p>{answerResult.detailed_analysis.correct_answer_explanation}</p>
                        </div>
                      )}
                      {answerResult.detailed_analysis.error_analysis && (
                        <div className="error-explanation">
                          <strong>❌ 错误分析：</strong>
                          <p>{answerResult.detailed_analysis.error_analysis}</p>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}

              {/* 学习建议 */}
              {answerResult.recommendations &&
                answerResult.recommendations.length > 0 && (
                  <div className="recommendations">
                    <h4>学习建议</h4>
                    <ul>
                      {answerResult.recommendations.map((rec, index) => (
                        <li key={index}>{rec}</li>
                      ))}
                    </ul>
                  </div>
                )}
            </div>

            {/* 导航按钮 */}
            <div className="result-actions">
              <button
                className="debate-button"
                onClick={async () => {
                  // 进入辩论模式
                  const currentQuestion = dailyQuestions[currentIndex]
                  if (currentQuestion) {
                    try {
                      const session = await debateApi.startDebate(
                        userId,
                        currentQuestion.question_id,
                        currentQuestion.content,
                        '中立',
                        currentQuestion.options || []
                      )
                      setDebateSession(session)
                      setShowDebate(true)
                    } catch (error) {
                      console.error('启动辩论失败:', error)
                    }
                  }
                }}
              >
                💬 进入辩论
              </button>
              <button
                className="nav-button"
                onClick={prevQuestion}
                disabled={currentIndex === 0}
              >
                上一题
              </button>
              {currentIndex < dailyQuestions.length - 1 ? (
                <button className="nav-button primary" onClick={nextQuestion}>
                  下一题
                </button>
              ) : (
                <button 
                  className="nav-button primary" 
                  onClick={async () => {
                    if (!planId) {
                      alert('请先创建学习计划')
                      return
                    }
                    
                    setIsLoading(true)
                    try {
                      // 获取今日统计
                      const statistics = await dailyLearningApi.getTodayStatistics(userId, planId) as any
                      
                      // 计算统计信息
                      const totalCompleted = statistics.total_completed || 0
                      const targetQuestions = statistics.target_questions || dailyQuestions.length
                      const correctCount = statistics.correct_count || 0
                      const wrongCount = statistics.wrong_count || 0
                      const accuracy = statistics.accuracy || 0
                      
                      // 显示统计并询问是否继续
                      const continueMessage = `📊 今日学习统计\n\n` +
                        `✅ 已完成题目：${totalCompleted}/${targetQuestions}\n` +
                        `✓ 正确：${correctCount} 题\n` +
                        `✗ 错误：${wrongCount} 题\n` +
                        `📈 正确率：${accuracy}%\n\n` +
                        `是否继续学习更多题目？`
                      
                      const shouldContinue = window.confirm(continueMessage)
                      
                      if (shouldContinue) {
                        // 继续学习，获取新的训练题目
                        const continueResult = await dailyLearningApi.continueLearning(userId, planId) as any
                        const newDailyTask = continueResult.daily_task
                        
                        if (newDailyTask && newDailyTask.questions && newDailyTask.questions.length > 0) {
                          // 更新题目列表
                          setDailyQuestions(newDailyTask.questions)
                          setCurrentIndex(0)
                          setSelectedAnswer('')
                          setSelectedAnswers([])
                          setAnswerResult(null)
                          setUserNotes('')
                          setMarkedWrong(false)
                          
                          alert(`已为您生成 ${newDailyTask.questions.length} 道新题目，继续加油！💪`)
                        } else {
                          alert('暂时没有更多题目，请稍后再试')
                        }
                      } else {
                        // 不继续，显示完成消息
                        alert(`今日学习完成！\n\n已完成 ${totalCompleted} 题，正确率 ${accuracy}%\n\n继续保持，明天继续加油！💪`)
                      }
                    } catch (error) {
                      console.error('完成今日学习失败:', error)
                      alert('获取统计信息失败，请稍后重试')
                    } finally {
                      setIsLoading(false)
                    }
                  }}
                  disabled={isLoading}
                >
                  {isLoading ? '处理中...' : '完成今日学习'}
                </button>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 辩论面板（模态显示） */}
      <AnimatePresence>
        {showDebate && dailyQuestions[currentIndex] && debateSession && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="debate-modal-overlay"
            onClick={() => setShowDebate(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="debate-modal-content"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="debate-modal-header">
                <h2>辩论训练</h2>
                <button
                  className="close-button"
                  onClick={() => setShowDebate(false)}
                >
                  ✕
                </button>
              </div>
              <div className="debate-modal-body">
                <DebatePanel
                  userId={userId}
                  questionId={dailyQuestions[currentIndex].question_id}
                  questionContent={dailyQuestions[currentIndex].content}
                  questionOptions={dailyQuestions[currentIndex].options}
                  onNavigate={(tab) => {
                    if (tab === 'daily-learning') {
                      setShowDebate(false)
                    }
                  }}
                />
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

export default DailyLearningPanel

